<?php

use think\facade\Log;
use app\api\service\Common;
use think\Request;

/**
 *  生成随机字符串
 */
function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for (
        $i = 0;
        $i < $length;
        $i++
    ) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}

/**
 *  生成验证码 6 位数字
 */
function getVerifyCode($length = 6)
{
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= mt_rand(0, 9);
    }
    return $code;
}

/**
 *  生成订单流水号
 */
function getRequestId() {}

/**
 * 获取客户端ip
 */
function getClientIP()
{
    $ip = '';
    foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
        if (!empty($_SERVER[$key])) {
            $ipList = explode(',', $_SERVER[$key]);
            foreach ($ipList as $potentialIp) {
                $potentialIp = trim($potentialIp);
                if (filter_var($potentialIp, FILTER_VALIDATE_IP)) {
                    $ip = $potentialIp;
                    break 2; // 取第一个有效IP
                }
            }
        }
    }
    return $ip;
}

/**
 * @describe
 * @author: Bobo
 * @date: 2025-05-26 10:51:11 
 * @param $data 需要翻译的数据 二维数组
 * @param $lang 语言 默认中文
 * @param $inFields 需要翻译的字段 默认['name']
 * @param $outFields 翻译后的字段 默认['translate_name']
 * @return Renderable
 */
function translate($data, $lang, $inFields = ['name'], $outFields = ['translate_name'])
{
    if (count($data) == 0) {
        return $data;
    }

    try {
        // 为每个需要翻译的字段生成翻译键
        $data = array_map(function ($item) use ($inFields) {
            foreach ($inFields as $field) {
                if (isset($item[$field])) {
                    $item['translate_key_' . $field] = md5($item[$field]);
                }
            }
            return $item;
        }, $data);
        $data = array_column($data, null, 'translate_key_' . $inFields[0]);

        // 收集所有需要翻译的内容
        $translateContent = [];
        foreach ($data as $key => $value) {
            foreach ($inFields as $field) {
                if (isset($value[$field]) && !empty($value[$field])) {
                    $translateContent[$value['translate_key_' . $field]] = $value[$field];
                }
            }
        }

        $translateService = new Common();
        $translateParams = [
            'content' => json_encode($translateContent),
            'target_language' => $lang
        ];

        $translateResult = $translateService->translate($translateParams);

        if (0 == $translateResult['code'] && !empty($translateResult['data'])) {
            foreach ($translateResult['data'] as $key => $value) {
                $key = trim($key, '"');
                // 找到对应的字段并设置到输出字段
                foreach ($inFields as $index => $inField) {
                    $fieldKey = 'translate_key_' . $inField;
                    $outField = $outFields[$index] ?? 'translate_' . $inField;
                    foreach ($data as $dataKey => $dataValue) {
                        if (isset($dataValue[$fieldKey]) && $dataValue[$fieldKey] === $key) {
                            $data[$dataKey][$outField] = $value;
                        }
                    }
                }
            }
        } else {
            Log::error('翻译失败,translateParams:' . json_encode($translateParams) . ',translateResult:' . json_encode($translateResult));
        }

        // 清理翻译键
        $data = array_map(function ($item) use ($inFields) {
            foreach ($inFields as $field) {
                unset($item['translate_key_' . $field]);
            }
            return $item;
        }, $data);

        $data = array_values($data);
        return $data;
    } catch (\Exception $e) {
        $errorMessage = sprintf(
            '翻译失败,translateParams:%s,error:%s',
            isset($translateParams) ? json_encode($translateParams) : '未生成',
            $e->getMessage()
        );
        Log::error($errorMessage);
        $data = array_values($data);
        return $data;
    }
}


function translateOne($data, $lang)
{
    if (empty($data)) {
        return $data;
    }
    $translateService = new Common();
    $translateParams = [
        'content' => json_encode([md5($data) => $data]),
        'target_language' => $lang
    ];

    $translateResult = $translateService->translate($translateParams);
    if (0 == $translateResult['code'] && !empty($translateResult['data'])) {
        return $translateResult['data'][md5($data)];
    } else {
        return $data;
    }
}


function getRealIp(Request $request)
{
    // IP获取优先级列表
    $ipSources = [
        ['type' => 'header', 'key' => 'X-Real-IP2'],
        ['type' => 'header', 'key' => 'X-Real-IP'],
        ['type' => 'server', 'key' => 'HTTP_X_FORWARDED_FOR'],
        ['type' => 'server', 'key' => 'REMOTE_ADDR']
    ];

    foreach ($ipSources as $source) {
        $ip = null;
        if ($source['type'] === 'header') {
            $ip = $request->header($source['key']);
        } elseif ($source['type'] === 'server') {
            $ip = $_SERVER[$source['key']] ?? null;
        }

        if ($ip && filter_var(trim($ip), FILTER_VALIDATE_IP) !== false) {
            return trim($ip);
        }
    }

    // 所有方法都失败时返回默认IP
    return '182.239.127.137';
}
